#include "hal.h"
#include <raw_api.h>

#if (HAL_USE_GPIO > 0)

HAL_ERROR gpio_init(GPIO_DRIVER *gpio) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	
	RAW_ASSERT(gpio != 0);
	
	mutex_error = raw_mutex_get(&gpio->gpio_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	ret = gpio_lld_init(gpio);

	mutex_error = raw_mutex_put(&gpio->gpio_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	return ret;
	
}


HAL_ERROR gpio_start(GPIO_DRIVER *gpio, GPIO_CONFIG *config)
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT((gpio != 0) && (config != 0));

	mutex_error = raw_mutex_get(&gpio->gpio_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	gpio->config = config;
	ret = gpio_lld_start(gpio, config);
	
	mutex_error = raw_mutex_put(&gpio->gpio_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	return ret;
}


HAL_ERROR gpio_stop(GPIO_DRIVER *gpio, RAW_U32 gpio_pin)
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(gpio != 0);

	mutex_error = raw_mutex_get(&gpio->gpio_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = gpio_lld_stop(gpio, gpio_pin);
	
	mutex_error = raw_mutex_put(&gpio->gpio_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	return ret;
}


HAL_ERROR gpio_pin_write(GPIO_DRIVER *gpio, RAW_U32 pin, GPIO_PIN_STATE pin_state)
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(gpio != 0);

	mutex_error = raw_mutex_get(&gpio->gpio_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = gpio_lld_pin_write(gpio, pin, pin_state);
	
	mutex_error = raw_mutex_put(&gpio->gpio_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;
}


HAL_ERROR gpio_pin_read(GPIO_DRIVER *gpio, RAW_U32 pin, GPIO_PIN_STATE *pin_value)
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(gpio != 0);

	mutex_error = raw_mutex_get(&gpio->gpio_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	ret = gpio_lld_pin_read(gpio, pin, pin_value);
	
	mutex_error = raw_mutex_put(&gpio->gpio_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;
}


HAL_ERROR gpio_deinit(GPIO_DRIVER *gpio) 
{
	HAL_ERROR ret;
	RAW_OS_ERROR mutex_error;
	
	RAW_ASSERT(gpio != 0);
	
	mutex_error = raw_mutex_get(&gpio->gpio_lock, RAW_WAIT_FOREVER);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);

	ret = gpio_lld_deinit(gpio);

	mutex_error = raw_mutex_put(&gpio->gpio_lock);
	RAW_ASSERT(mutex_error == RAW_SUCCESS);
	
	return ret;
	
}


#endif


